package com.mlethe.library.utils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池管理类
 * Created by Mlethe on 2018/1/11.
 */
public class ThreadPoolUtil {

    private ExecutorService fixedThreadPool;

    private ThreadPoolUtil() {
    }

    private static final class Holder {
        private static final ThreadPoolUtil INSTANCE = new ThreadPoolUtil();
    }

    public static ThreadPoolUtil getInstance() {
        return Holder.INSTANCE;
    }

    /**
     * 设置线程池大小
     *
     * @param count
     * @return
     */
    public void setPoolCount(int count) {
        if (count <= 0) {
            count = 1;
        } else if (count > Runtime.getRuntime().availableProcessors()) {
            count = Runtime.getRuntime().availableProcessors();
        }
        if (fixedThreadPool != null) {
            try {
                fixedThreadPool.shutdown();
                // (所有的任务都结束的时候，返回TRUE)
                if (!fixedThreadPool.awaitTermination(2000, TimeUnit.MILLISECONDS)) {
                    // 超时的时候向线程池中所有的线程发出中断(interrupted)。
                    fixedThreadPool.shutdownNow();
                }
            } catch (InterruptedException e) {
                // awaitTermination方法被中断的时候也中止线程池中全部的线程的执行。
                fixedThreadPool.shutdownNow();
            }
            fixedThreadPool = null;
        }
        fixedThreadPool = new ThreadPoolExecutor(count, count,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
    }

    /**
     * 给线程池添加任务
     *
     * @param runnable 任务
     */
    public void execute(Runnable runnable) {
        if (fixedThreadPool != null) {
            fixedThreadPool.execute(runnable);
        }
    }

}
